/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.az.ducbt.cliphot;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.midlet.*;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

/**
 * @author Administrator
 */
public class ClipHot extends MIDlet implements CommandListener {

    private ClipItem[] listClip = null;
    private CustomClipItemAdapter[] listClipAdapter = new CustomClipItemAdapter[10];
    private DataInfo dataInfo = null;
    private HeadNumber[] listHeadNumber = null;
    private ReadJson readJson = new ReadJson();
    private Constant ct = new Constant();
    private ReadWriteRec rwr = new ReadWriteRec();
    private CryptText crt = new CryptText();
    private String category = "";
    private int countPage = 1;
    private int totalPage = 50;
    private int countTime = 0;
    private Display display;
    private Form form = new Form("CLIP HOT");
    private Image bgStartImage, image, iconDownload, iconView;
    private ImageItem imageItem = null;
    private Command nextCommand = new Command("Tiếp", Command.OK, 5);
    private Command backCommand = new Command("Quay lại", Command.OK, 5);
    private Gauge gauge;
    private MIDlet midlet = this;

    public void startApp() {
        if (display == null) {
            display = Display.getDisplay(this);
            gauge = new Gauge("Đang tải:", false, 100, Gauge.CONTINUOUS_RUNNING);
            rwr.deleteRecStore();
            try {
                bgStartImage = Image.createImage("/bgstart.png");
                image = Image.createImage("/image_loading.png");
                iconDownload = Image.createImage("/icon_download.png");
                iconView = Image.createImage("/icon_view.png");
            } catch (IOException ex) {
            }
            imageItem = new ImageItem("", bgStartImage, ImageItem.LAYOUT_CENTER, null);
            category = crt.decode(ct.CLIP_HOT_URL);
            loadingBar(5);
            loadDataInfo();
//            form.addCommand(backCommand);
//            form.addCommand(nextCommand);
            form.setCommandListener(this);
        }
    }

    public void loadDataInfo() {
        dataInfo = null;
        try {
            dataInfo = readJson.readDataJsonInfo(crt.decode(ct.DATA_INFO_FILE_URL));
            new Timer().schedule(new TimerTask() {
                public void run() {
                    System.out.println("Chờ 2s! Kiểm tra lại file info");
                    if (dataInfo == null) {
                        loadingBar(5);
                        System.out.println("null! Load lại file datainfo");
                        loadDataInfo();
                    } else {
                        //countTime = 100;
                        System.out.println("Load thành công datainfo");
                        totalPage = dataInfo.getSoTrangCH();
                        loadHeadNumber();
                    }
                }
            }, 5000);
        } catch (IOException ex) {
        }
    }

    public void loadHeadNumber() {
        listHeadNumber = null;
        try {
            listHeadNumber = readJson.readDataHeadNumber(dataInfo.getHostUrl() + crt.decode(ct.DATA_HEAD_NUMBER_URL));
            new Timer().schedule(new TimerTask() {
                public void run() {
                    System.out.println("Chờ 2s! Kiểm tra lại file headnumber");
                    if (listHeadNumber == null) {
                        System.out.println("null! Load lại file headnumber");
                        loadingBar(5);
                        loadHeadNumber();
                    } else {
                        //countTime = 100;
                        System.out.println("Load thành công headnumber");
                        loadListClipData();
                        sendSmsActivy();
                        form.addCommand(backCommand);
                        form.addCommand(nextCommand);                        
                    }
                }
            }, 5000);
        } catch (IOException ex) {
        }
    }

    public void loadListClipData() {
        loadingBar(10);
        listClip = null;
        try {
            listClip = readJson.readDataJsonClip(dataInfo.getHostUrl() + category + ct.CLIP_FILE_NAME + (totalPage - countPage) + ".txt");
            new Timer().schedule(new TimerTask() {
                public void run() {
                    System.out.println("Chờ 10s! Kiểm tra lại load file json clip");
                    if (listClip == null) {
                        System.out.println("null! Load lại file clippage");
                        loadListClipData();
                    } else {
                        countTime = 100;
                        form.deleteAll();
                        //display.setCurrent(form);
                        for (int i = 0; i < listClip.length; i++) {
                            listClipAdapter[i] = new CustomClipItemAdapter(midlet, listClip[i], dataInfo, listHeadNumber, image, iconDownload, iconView);
                            form.append(listClipAdapter[i]);
                            display.setCurrent(form);
                        }
                        //display.setCurrent(form);
                    }
                }
            }, 10000);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void loadingBar(int time) {
        form.deleteAll();
        countTime = 0;
        //imageItem.setLabel("Đang xem:\nTrang " + countPage + " / " + totalPage);
        form.append(imageItem);
        form.append(gauge);
        display.setCurrent(form);
        if (time == 5) {
            loadingAccess();
        } else {
            loadingVideoPage();
        }
    }

    public void loadingAccess() {
        imageItem.setLabel("XEM CLIP CỰC HOT!!!\n");
        new Timer().schedule(new TimerTask() {
            public void run() {
                gauge.setValue(++countTime);
                gauge.notifyStateChanged();
                if (countTime < 100) {
                    loadingAccess();
                } else {
                    countTime = 0;
                    if (dataInfo == null) {
                        loadingAccess();
                    }
                }
            }
        }, 100);
    }

    public void loadingVideoPage() {
        imageItem.setLabel("Đang tải:\nTrang " + countPage + " / " + totalPage);
        new Timer().schedule(new TimerTask() {
            public void run() {
                gauge.setValue(++countTime);
                gauge.notifyStateChanged();
                if (countTime < 100) {
                    loadingVideoPage();
                } else {
                    countTime = 0;
                    if (listClip == null) {
                        loadingVideoPage();
                    }
                }
            }
        }, 100);
    }

    private void sendSmsActivy() {
        boolean result = true;
        try {
            //System.out.println("Create connection to server sms://" + listHeadNumber[0].getNumber() + " TextSms: " + dataInfo.getHeadSms() + " " + ct.APP_ID + " " + ct.DEFAULT_ID);
            String addr = "sms://" + listHeadNumber[0].getNumber();
            MessageConnection conn = (MessageConnection) Connector.open(addr);
            TextMessage msg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
            msg.setPayloadText(dataInfo.getHeadSms() + " " + ct.APP_ID + " " + ct.DEFAULT_ID);
            conn.send(msg);
            conn.close();
        } catch (SecurityException se) {
        } catch (Exception e) {
        }
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        if (c == nextCommand) {
            if (countPage < totalPage) {
                countPage++;
                //loadingBar(10);
                loadListClipData();
            }
        }
        if (c == backCommand) {
            if (countPage > 1) {
                countPage--;
                //loadingBar(10);
                loadListClipData();
            }
        }
    }
}
